<template>
	<!-- 维保合同 添加/编辑/详情 -->
	<div class="compile">
		<el-dialog :close-on-click-modal='false' :append-to-body='true' :before-close='close' :close-on-press-escape='false'
		 :title="title" :visible.sync="addAndCompileShow">
			<el-form :model="form" :rules="rules" ref="form" v-loading='isLoading'>
				<el-row>
					<div class="textLeft titleMessNow">合同信息</div>
				</el-row>
				<el-row>
					<el-col :span="10" :offset='1'>
						<el-form-item label="合同名称:" :label-width="formLabelWidth" prop="pactName">
							<el-input size="mini" v-model="form.pactName" autocomplete="off" clearable :disabled='detailDisable'></el-input>
						</el-form-item>
					</el-col>
					<el-col :span="10" :offset='2'>
						<el-form-item label="合同编号:" :label-width="formLabelWidth" prop="pactNum">
							<el-input size="mini" v-model="form.pactNum" autocomplete="off" clearable :disabled='detailDisable'></el-input>
						</el-form-item>
					</el-col>
				</el-row>
				<el-row>
					<el-col :span="10" :offset='1'>
						<el-form-item label="合同类型:" :label-width="formLabelWidth" prop="pactType">
							<el-select size="mini" v-model="form.pactType" placeholder="请选择合同类型" clearable :disabled='detailDisable'>
								<el-option v-for="item in contract_type" :value="item.value" :label="item.label" :key='item.value'>
								</el-option>
							</el-select>
						</el-form-item>
					</el-col>
					<el-col :span="10" :offset='2'>
						<el-form-item label="签署日期:" :label-width="formLabelWidth" prop="mainDate">
							<el-date-picker size="mini" v-model="form.mainDate" type="date" placeholder="请选择签署日期" format="yyyy-MM-dd"
							 value-format="yyyy-MM-dd" clearable :disabled='detailDisable'>
							</el-date-picker>
						</el-form-item>
					</el-col>
				</el-row>
				<el-row>
					<el-col :span="10" :offset='1'>
						<el-form-item label="合同开始日期:" :label-width="formLabelWidth" prop="pactStartTime">
							<el-date-picker size="mini" v-model="form.pactStartTime" type="date" placeholder="请选择合同开始日期" format="yyyy-MM-dd"
							 value-format="yyyy-MM-dd" clearable :disabled='detailDisable' @change="startTimeChange">
							</el-date-picker>
						</el-form-item>
					</el-col>
					<el-col :span="10" :offset='2'>
						<el-form-item label="合同结束日期:" :label-width="formLabelWidth" prop="pactEndTime">
							<el-date-picker size="mini" v-model="form.pactEndTime" type="date" placeholder="请选择合同结束日期" format="yyyy-MM-dd"
							 value-format="yyyy-MM-dd" clearable :disabled='isDis'  :picker-options="pickerOptions">
							</el-date-picker>
						</el-form-item>
					</el-col>
				</el-row>
				<el-row>
					<el-col :span="10" :offset="1">
						<el-form-item label="合同附件:" :label-width="formLabelWidth" prop="pactAffix">
							<el-upload :on-preview="upLoadPreview" action="" accept=".jpg,.jpeg,.png" :file-list="fileList" :on-change="upLoadChange"
							 :on-remove="upLoadRemove" :auto-upload="false" list-type="picture" name="upfile" :disabled='detailDisable'>
								<el-button size="mini" type="primary" :disabled='detailDisable'>点击上传合同附件</el-button>
								<div slot="tip" class="upLoadText">只能上传JPG/PNG/JPEG图片,大小不超过800kb/最多上传10张</div>
							</el-upload>
						</el-form-item>
					</el-col>
				</el-row>

				<el-row>
					<div class="textLeft titleMessNow">单位信息</div>
				</el-row>
				<el-row>
					<el-col :span="10" :offset='1'>
						<el-form-item label="维保单位:" :label-width="formLabelWidth" prop="company">
							<el-select size="mini" v-model="form.company" placeholder="请选择维保单位" clearable :disabled='detailDisable'>
								<el-option v-for="item in companyUnitArr" :value="item.value" :label="item.label" :key='item.value'>
								</el-option>
							</el-select>
						</el-form-item>
					</el-col>
					<el-col :span="10" :offset='2'>
						<el-form-item label="使用单位:" :label-width="formLabelWidth" prop="userUnit">
							<el-select size="mini" @focus="getUserUnit" :remote-method="findUserUnit" filterable remote v-model="form.userUnit"
							 placeholder="请选择使用单位" clearable :disabled='detailDisable'>
								<el-option v-for="item in userUnitArr" :value="item.id" :label="item.label" :key='item.id'>
								</el-option>
							</el-select>
						</el-form-item>
					</el-col>
				</el-row>
				<!-- 选择电梯 -->
				<el-row>
					<div class="textLeft titleMessNow">选择电梯</div>
				</el-row>
				<el-row>
					<el-col :span="16" :offset='1'>
						<el-form-item label="维保电梯:" :label-width="formLabelWidth" prop="liftUnit">
							<el-select multiple size="mini" @focus="getLiftUnit" :remote-method="findLiftUnit" filterable remote v-model="form.liftUnit"
							 placeholder="请选择维保维保电梯" clearable :disabled='detailDisable'>
								<el-option v-for="item in liftUnitArr" :value="item.id" :label="item.register_code" :key='item.id'>
								</el-option>
							</el-select>
						</el-form-item>
					</el-col>
					<el-col :offset='2' :span="4">
						<div style="margin-top: 10px;">已选择电梯数量：{{form.liftUnit.length}}</div>
					</el-col>
				</el-row>
				<!-- 匹配结果 -->
				<div v-if="detailDisable">
					<el-row>
						<div class="textLeft titleMessNow">匹配结果</div>
					</el-row>
					<el-row>
						<el-col :span="16" :offset='1'>
							<el-form-item label="更新状态:" :label-width="formLabelWidth">
								<el-input size="mini" v-model="updataType" autocomplete="off" clearable :disabled='detailDisable'></el-input>
							</el-form-item>
						</el-col>
					</el-row>
					<el-row>
						<el-col :span="16" :offset='1'>
							<el-form-item label="最后更新时间" :label-width="formLabelWidth">
								<el-date-picker size="mini" v-model="lastUpdataTime" type="date" placeholder="请选择最后更新时间" format="yyyy-MM-dd HH:mm:ss"
								 value-format="yyyy-MM-dd HH:mm:ss" clearable :disabled='detailDisable'>
								</el-date-picker>
							</el-form-item>
						</el-col>
					</el-row>

					<div class="div" v-if="roleId == 0">
						<el-row>
							<div class="textLeft titleMessNow">备案原始数据</div>
						</el-row>
						<el-row>
							<el-col :span="16" :offset="1">
								<div class="copy" id="content">
									{{recordCon}}
								</div>
								<el-button type="primary" style="margin-left: 170px;margin-top:15px" @click="copy">复制所有请求信息</el-button>
							</el-col>
						</el-row>
						<el-row>
							<el-col :span="16" :offset="1">
								<div class="copy" id="content1">
									{{recordCon1}}
								</div>
								<el-button type="primary" style="margin-left: 170px;margin-top:15px" @click="copy1">复制所有返回信息</el-button>
							</el-col>
						</el-row>
					</div>
				</div>
			</el-form>

			<div slot="footer" class="dialog-footer">
				<el-button @click="close(2)">取 消</el-button>
				<el-button type="primary" @click="submit('form')" v-loading='ensureBtn' v-if="!detailDisable">确 定</el-button>
			</div>
		</el-dialog>

		<el-dialog custom-class="imgDialogShow" :visible.sync="imgDialogShow" :append-to-body='true' :before-close='closeImg'>
			<img :src="dialogImgUrl" alt="">
		</el-dialog>
	</div>
</template>

<script>
	import {
		axiosPost,
		axiosGet,
		loadFn,
		axiosChange,
		moment
	} from "@/common.js"
	import {
		pactName,
		pactType,
		pactNum,
		pactStartTime,
		pactEndTime,
		mainDate,
		company,
		userUnit,
		liftUnit,
	} from "./rule.js"
	export default {
		props: ['addAndCompileShow', 'isAddOrComp', 'rowId'],
		mounted() {
			this.getUserUnit()
			if (this.title == '添加维保合同') {
				this.isLoading = false
			}
		},
		data() {
			var valiPic = (rule, value, callback) => {
				if (this.fileList.length === 0) {
					console.log(this.fileList.length)
					callback(new Error('请上传合同附件照片'));
				} else {
					callback();
				}
			};
			return {
				formLabelWidth: '120px',
				form: {
					pactName: '',
					pactType: '',
					pactNum: '',
					pactStartTime: '',
					pactEndTime: '',
					mainDate: '',
					userName: '',
					userUnit: '',
					company: localStorage.company_id ? JSON.parse(localStorage.company_id).id : '',
					liftUnit: []
				},
				dialogFormVisible: true,
				ensureBtn: false,
				imgDialogShow: false,
				dialogImgUrl: '',
				rules: {
					pactName,
					pactType,
					pactNum,
					pactStartTime,
					pactEndTime,
					mainDate,
					company,
					userUnit,
					liftUnit,
					pactAffix: [{
						required: true,
						trigger: 'blur',
						validator: valiPic
					}],
				},
				contract_type: [{
					value: 20,
					label: "保养"
				}, ],
				fileList: [],
				userUnitArr: [],
				liftUnitArr: [],
				loading: true,
				imgArr: [],
				updataType: '',
				lastUpdataTime: '',
				recordCon: '',
				recordCon1: '',
				isLoading: true,
				companyUnitArr: localStorage.company_name ? [{
					label: JSON.parse(localStorage.company_name).name,
					value: JSON.parse(localStorage.company_id).id,
				}] : []
			}
		},
		computed: {
			isDis(){
				if(this.form.pactStartTime){
					return false
				}else{
					return true
				}
			},
				//控制结束时间范围
			pickerOptions() {
				return {
					disabledDate: (time) => {
						return time.getTime() < moment(this.form.pactStartTime)
					}
				}
			},
			detailDisable() {
				if (this.title == '维保合同详情') {
					return true
				} else {
					return false
				}
			},
			title() {
				if (this.isAddOrComp == 1) {
					return '添加维保合同'
				} else if (this.isAddOrComp == 2) {
					this.getCompileList()
					return '编辑维保合同'
				} else {
					this.getCompileList()
					return '维保合同详情'
				}
			},
			disableLift() {
				if (!!this.form.userUnit) {
					return false
				} else {
					return true
				}
			},
			roleId() {
				if (localStorage.role) {
					return JSON.parse(localStorage.role).id
				} else {
					return ''
				}
			},
		},
		methods: {
			//开始时间变化
			startTimeChange(){
				this.form.pactEndTime = ''
			},
			copy() {
				/* 创建range对象   */
				const range = document.createRange();
				range.selectNode(document.getElementById('content'));

				/* 窗口的selection对象，表示用户选择的文本 */
				const selection = window.getSelection();
				if (selection.rangeCount > 0) selection.removeAllRanges(); // 将已经包含的已选择的对象清除掉
				selection.addRange(range); // 将要复制的区域的range对象添加到selection对象中

				document.execCommand('copy'); // 执行copy命令，copy用户选择的文本
			},
			copy1() {
				/* 创建range对象   */
				const range = document.createRange();
				range.selectNode(document.getElementById('content1'));

				/* 窗口的selection对象，表示用户选择的文本 */
				const selection = window.getSelection();
				if (selection.rangeCount > 0) selection.removeAllRanges(); // 将已经包含的已选择的对象清除掉
				selection.addRange(range); // 将要复制的区域的range对象添加到selection对象中

				document.execCommand('copy'); // 执行copy命令，copy用户选择的文本
			},
			//获取使用单位
			userPublic(params) {
				axiosGet('/user/company/all', params, (res) => {
					if (res.code == 0) {
						this.userUnitArr = res.detail.results
					} else {
						this.$message.error(res.detail.result)
					}
				})
			},
			getUserUnit() {
				let params = {
					company_type: 300,
					page_size_count: 30
				}
				this.userPublic(params)
			},
			//使用单位开启搜索
			findUserUnit(query) {
				console.log(query)
				let params = {
					company_type: 300,
					key_words: query
				}
				this.userPublic(params)
			},
			//公共函数
			liftPublic(params, url) {
				axiosGet(url, params, (res) => {
					if (res.code == 0) {
						this.liftUnitArr = res.detail.results
					} else {
						this.$message.error(res.detail.result)
					}
				})
			},
			//获取电梯
			getLiftUnit() {
				let params = {
					page_size_count: 30
				}
				let url = '/basic/elevator/choice/'
				this.liftPublic(params, url)
			},
			//电梯开启搜索
			findLiftUnit(query) {
				console.log(query)
				let params = {
					key_words: query,
					page_size_count: 30
				}
				let url = '/basic/elevator/'
				this.liftPublic(params, url)
			},
			//点击图片时触发
			upLoadPreview(file) {
				console.log(file)
				this.imgDialogShow = true
				this.dialogImgUrl = file.url
			},
			//上传文件之前触发
			upLoadChange(file, fileList) {
				const isLt2M = file.size / 1024 < 800;
				if (file.name.split(".")[1] != "jpg" && file.name.split(".")[1] != "png" && file.name.split(".")[1] != "jpeg") {
					this.$message.error('只能上传JPG/PNG/JPEG格式图片');
					this.fileList = fileList.slice(0, -1);
					return
				}
				if (!isLt2M) {
					this.$message.error('上传图片大小不能超过 800kb!,请重新上传');
					this.fileList = fileList.slice(0, -1);
					return
				}
				this.fileList = fileList.slice(-10);
			},
			//删除文件之前的函数
			upLoadRemove(file, fileList) {
				this.fileList = fileList;
				console.log(this.fileList)
			},
			//上传照片接口
			uploadImage(imgList, num) {
				if (imgList.leng != 0) {
					const formData = new FormData();
					formData.append("upfile", imgList[num].raw)
					return this.$axios({
						url: "/utils/upload/",
						method: "post",
						data: formData
					})
				} else {
					console.log('没有照片')
				}
			},
			//合同公共函数
			async oprationUintPub(value) {
				this.imgArr = []
				let permises = []
				for (let i = 0; i < this.fileList.length; i++) {
					if (this.fileList[i].raw) {
						permises.push(this.uploadImage(this.fileList, i))
					} else {
						this.imgArr.push(this.fileList[i].url)
					}
				}
				const res = await Promise.all(permises)
				for (let i = 0; i < res.length; i++) {
					res[i].code == 0 && this.imgArr.push(res[i].detail)
				}
				let data = {
					contract_file: this.imgArr,
					contract_name: this.form.pactName,
					contract_no: this.form.pactNum,
					contract_type: this.form.pactType,
					start_time: this.form.pactStartTime,
					end_time: this.form.pactEndTime,
					sign_time: this.form.mainDate,
					maintain_company: this.form.company,
					property_company: this.form.userUnit,
					maintain_cycle: 10,
					elevator_info: this.form.liftUnit,
				}
				if (value == 1) {
					this.addUserPlan('/maintain/contract/', 'post', data)
				} else {
					let rowId = this.rowId
					let url = '/maintain/contract/' + rowId + '/'
					this.addUserPlan(url, 'put', data)
				}
			},
			//获取编辑/详情数据
			getCompileList() {
				let rowId = this.rowId
				let url = '/maintain/contract/' + rowId + '/'
				axiosGet(url, {}, (res) => {
					this.isLoading = false
					if (res.code == 0) {
						this.companyUnitArr = [{
							value: res.detail.maintain_company,
							label: res.detail.maintain_company_name
						}]
						this.form.company = res.detail.maintain_company
						this.fileList = res.detail.contract_file.map(item => ({
							name: '',
							url: item
						}))
						this.imgArr = res.detail.contract_file
						this.form.pactName = res.detail.contract_name
						this.form.pactNum = res.detail.contract_no
						this.form.pactType = res.detail.contract_type
						this.form.pactStartTime = res.detail.start_time
						this.form.pactEndTime = res.detail.end_time
						this.form.mainDate = res.detail.sign_time
						this.form.company = res.detail.maintain_company
						this.form.userUnit = res.detail.property_company
						let message = !!res.detail.record.rec_status ? '更新成功' : '更新失败'
						this.updataType = message + '/' + res.detail.record.msg
						this.lastUpdataTime = res.detail.record.rec_end_time
						if (Object.keys(res.detail.record).length > 0) {
							if (!!res.detail.record.ret_info) {
								this.recordCon1 = res.detail.record.ret_info
							} else {
								this.recordCon1 = {}
							}
							if (!!res.detail.record.reg_info) {
								this.recordCon = res.detail.record.reg_info
							} else {
								this.recordCon = {}
							}
						}
						this.userUnitArr = []
						this.userUnitArr.push({
							id: res.detail.property_company,
							label: res.detail.property_company_name
						})

						this.form.liftUnit = res.detail.elevator_info.map((item) => {
							return item.elevator
						})
						this.liftUnitArr = []
						this.liftUnitArr.push(...res.detail.elevator_info.map((item) => {
							return {
								id: item.elevator,
								register_code: item.register_code
							}
						}))
					} else {
						this.$message.error(res.detail.result)
					}
				})
			},
			//添加合同
			addUserPlan(url, method, data) {
				axiosChange(url, method, data, (res) => {
					console.log(res)
					this.ensureBtn = false
					if (res.code == 0) {
						this.close(1)
						this.$message({
							type: 'success',
							message: '操作成功'
						})
					} else {
						this.$message.error(res.detail.result)
					}
				})
			},
			//提交
			submit(ruleForm) {
				this.$refs[ruleForm].validate((valid) => {
					if (valid) {
						if (this.form.pactStartTime > this.form.pactEndTime) {
							this.$message.error('合同开始时间不能大于合同结束时间')
							return false
						}
						this.ensureBtn = true
						if (this.isAddOrComp == 1) {
							this.oprationUintPub(1)
						} else {
							this.oprationUintPub(2)
						}
					} else {
						console.log('error submit!!');
						return false;
					}
				});
			},
			//关闭
			close(value) {
				let newValue = 2
				if (value) {
					newValue = value
				}
				console.log(newValue)
				this.$emit('detailMaskShow', newValue)
			},
			closeImg() {
				this.imgDialogShow = false
			},
		}
	}
</script>
<style scoped lang="less">
</style>
